package com.difsonapps.android.joinme.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import com.difsonapps.android.joinme.GlobalVariables;
import com.difsonapps.android.joinme.util.NetUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

public class Server extends AsyncTask<Object, Object, Object>{

	private ServerSocket serverSocket;

	Handler updateConversationHandler;

	Thread serverThread = null;

	public static final int SERVERPORT = 8000;


	@Override
	protected Object doInBackground(Object... params) {
		this.serverThread = new Thread(new ServerThread());
		this.serverThread.start();
		return null;
	}
	

	class ServerThread implements Runnable {

		public void run() {
			Socket socket = null;
			Log.d("Server", "the server is initialized");
			try {
				serverSocket = new ServerSocket(SERVERPORT);
				Log.d("Server", "LocalPort : " + serverSocket.getLocalPort() + "   IP Address: " + NetUtils.getIPAddress(true));
				new UpdateStatus(new String[] {"5", "true", NetUtils.getIPAddress(true), "8000"} );
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			while (!Thread.currentThread().isInterrupted()) {

				try {

					socket = serverSocket.accept();

					CommunicationThread commThread = new CommunicationThread(socket);
					new Thread(commThread).start();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class CommunicationThread implements Runnable {

		private Socket clientSocket;

		private BufferedReader input;

		public CommunicationThread(Socket clientSocket) {

			this.clientSocket = clientSocket;

			try {

				this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void run() {

			while (!Thread.currentThread().isInterrupted()) {

				try {

					String read = input.readLine();

					updateConversationHandler.post(new updateUIThread(read));

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	class updateUIThread implements Runnable {
		private String msg;

		public updateUIThread(String str) {
			this.msg = str;
		}

		@Override
		public void run() {
			Log.d("Client: ", msg);
		}
	}


}